<?php

/**
 * 命令行执行，定时任务
 * @noinspection ForgottenDebugOutputInspection
 */

require './comm.php';

use Workerman\Worker;
use Workerman\Lib\Timer;
use Workerman\Autoloader;
use Workerman\Events\EventInterface;
use Workerman\Protocols\Http\Request;
use Workerman\Protocols\Http\Response;
use Workerman\Http\Client as HttpClient;
use Workerman\Redis\Client as RedisClient;

//每个进程最多执行x个请求
const MAX_REQUEST = 5;

Worker::$logFile = ROOT_PATH.'runtime/log/task.log';
Worker::$pidFile = ROOT_PATH.'runtime/pid_task.log';

$worker = new Worker();

$worker->name = 'MyTask1';

//启动x个进程 对外提供服务
$worker->count = 2;

$worker->onWorkerStart = function($worker)
{
    $workerId = $worker->id;

    echo PHP_EOL. "#$workerId 进程已启动" .PHP_EOL;

    //只在 id 为 0 的进程上执行：
    if($workerId === 0) {
        // todo...
    }

    $timeInterval = 1; //每x秒执行一次

    //全局定时器，如果设置了多个进程，则每个进程都会执行：
    $timerId = Timer::add($timeInterval, function() use (&$timerId, $workerId)
    {
        static $count = 0; $count++;
        $time = date('H:i:s');

        if($count >= MAX_REQUEST) {
            Timer::del($timerId);
            Worker::stopAll(); // Windows 会退出当前进程；Linux 会重启当前进程和子进程。
        }

        echo PHP_EOL. "[$workerId] $count. task run at $time" .PHP_EOL;
    });
};

$worker->onError = function ($connection, $code, $message)
{
    echo PHP_EOL. "error: [$code] $message" .PHP_EOL;
    $connection->errorCode = $code;
    $connection->close();
};

Worker::runAll();
